<template>
	<!-- 新增出料>>>原料区 -->
	<view class="container">
		<topBar isFixed>新增出料</topBar>
		<scroll-view scroll-y class="content">
			<view class="cart-imgs">
				<view class="left">
					<view class="title">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>车辆照片</text>
					</view>
					<view class="upload-area">
						<view class="upload-box" @click="uploadCartImg">
							<view class="upload">
								<image src="/static/img/common/camera.png" class="icon"></image>
								<text>拍照上传</text>
							</view>
							<view class="upload-tip">
								最多上传1张
							</view>
						</view>
						<view class="show-img" v-if="dischargingInfo.carImages[0]">
							<view class="imgs">
								<image :src="dischargingInfo.carImages[0]" mode="widthFix" class="img"></image>
							</view>
							<!-- <view class="img-title">
									物料照片01.jpg
								</view> -->
						</view>
					</view>
				</view>
				<view class="upload-example">
					<image src="/static/img/consumption/upload-example.png" class="img"></image>
					<view class="example-tip">
						上传示例
					</view>
				</view>
			</view>
			<view class="cart-info">
				<view class="cart-types">
					<Button2 class="btn" v-if="cartInfo.plateNoType">{{cartInfo.plateNoType}}</Button2>
					<Button2 class="btn" v-if="cartInfo.directory">{{cartInfo.directory}}</Button2>
				</view>
				<CarPlateInput :plateNumber="plateNumber" @PlateChange="handleNumChange" />
				<view class="cart-type">
					新能源
				</view>
			</view>
			<view class="cart-lines">
				<view class="line">
					<view class="title">
						运企名称
					</view>
					<view class="val">
						{{cartInfo.companyName}}
					</view>
				</view>
				<view class="line">
					<view class="title">
						起点名称
					</view>
					<view class="val">
						{{dischargingInfo.startingPlace}}
					</view>
				</view>
				<view class="line">
					<view class="title">
						起点厂区
					</view>
					<view class="val">
						{{startingPlace}}
					</view>
				</view>
				<view class="line">
					<view class="left">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>起点场所</text>
					</view>
					<view class="right">
						<block v-if="startVenueList.length">
							<Button1 v-for="item in startVenueList" :key="item.id"
								:class="item.label !== dischargingInfo.startingArea && 'no-active-btn'"
								@click="changeVenue1(item)">
								{{item.label}}
							</Button1>
						</block>
						<view class="val" v-else>
							{{dischargingInfo.startingArea}}
						</view>
					</view>
				</view>
				<view class="line">
					<view class="left">
					</view>
					<view class="right">
						<Button1 v-for="item in orderTypeList" :key="item.id"
							:class="item.id != dischargingInfo.orderEnd && 'no-active-btn'"
							@click="changeOrderType(item.id)">{{item.name}}</Button1>
					</view>
				</view>

				<view class="line" v-if="nowTerminusPlace !==''">
					<view class="title">
						终点厂区
					</view>
					<view class="val">
						生产区
					</view>
				</view>
				<view class="line" @click="showStartProjectPopup" v-else>
					<view class="title">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>终点名称</text>
					</view>
					<view class="val" :class="dischargingInfo.terminusPlace=='' &&'no-check'">
						<text>{{dischargingInfo.terminusPlace || '请选择' }}</text>
						<uni-icons type="right" size="28"
							:color="dischargingInfo.terminusPlace=='' ? '#989DA5' : '#0E1624'"></uni-icons>
					</view>
				</view>
				<view class="line" v-if="isShowTerminusArea">
					<view class="left">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>终点场所</text>
					</view>
					<view class="right">
						<block v-if="endVenueList.length">
							<Button1 v-for="item in endVenueList" :key="item.id"
								:class="item.label !== dischargingInfo.terminusArea && 'no-active-btn'"
								@click="changeVenue2(item)">
								{{item.label}}
							</Button1>
						</block>
						<view class="val" v-else>
							{{dischargingInfo.terminusArea}}
						</view>
					</view>
				</view>
				<view class="line">
					<view class="left">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>驾驶员</text>
					</view>
					<view class="val">
						<input type="text" class="amount-input" placeholder="请输入"
							v-model="dischargingInfo.driverName" />
					</view>
				</view>
				<view class="line" @click="showMaterialTypePopup">
					<view class="title">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>物料类型</text>
					</view>
					<view class="val" :class="dischargingInfo.rockName == '' &&'no-check'">
						<text>{{dischargingInfo.rockName || '请选择'}}</text>
						<uni-icons type="right" size="28"
							:color="dischargingInfo.rockName == ''?'#989DA5':'#0E1624'"></uni-icons>
					</view>
				</view>
				<view class="cart-imgs line ">
					<view class="left">
						<view class="title">
							物料照片
						</view>
						<view class="upload-area">
							<view class="upload-box" @click="uploadMaterialImg('rockImages')">
								<view class="upload">
									<image src="/static/img/common/camera.png" class="icon"></image>
									<text>拍照上传</text>
								</view>
								<view class="upload-tip">
									最多上传6张
								</view>
							</view>
							<view class="show-img" v-if="dischargingInfo.rockImages.length">
								<view class="imgs">
									<image v-if="dischargingInfo.rockImages[0]" :src="dischargingInfo.rockImages[0]"
										mode="widthFix" class="img"></image>
									<image v-if="dischargingInfo.rockImages[1]" :src="dischargingInfo.rockImages[1]"
										mode="widthFix" class="img"></image>
								</view>
								<view class="moreImg" @click="isShowMoreImgs = true">
									点击查看更多
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="line">
					<view class="title">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>是否满载</text>
					</view>
					<view class="val">
						<Button1 v-for="item in fullFlagList"
							:class="item.id != dischargingInfo.fullFlag && 'no-active-btn'" :key="item.id"
							@click="changeFullFlag(item.id)">
							{{item.name}}
						</Button1>
					</view>
				</view>
				<view class="line" v-if="dischargingInfo.fullFlag == 0">
					<view class="title">
						<image src="/static/img/common/required.png" class="required-icon"></image>
						<text>扣方方量</text>
					</view>
					<view class="val deduction-amount">
						-
						<input class="amount-input" type="number" v-model="dischargingInfo.volumeReduce"
							placeholder-style="color:#EB4F51;" placeholder="请输入" />
						方
					</view>
				</view>
			</view>

		</scroll-view>
		<!-- 终点名称弹窗 -->
		<StartProjectPopup v-if="isShowStartProjectPopup" isEnd :address-list="addressList"
			@saveStartProject="saveStartProject" />

		<!-- 物料类型弹窗 -->
		<MaterialTypePopup v-if="isShowMaterialTypePopup" :type-list="muckTypeList"
			@saveMaterialType="saveMaterialType" />
		<!-- 预览图片 -->
		<PreviewImgs :img-list="dischargingInfo.rockImages" v-if="isShowMoreImgs" @closePreview="closeMoreImgs" />

		<BottomBtn @click="saveReceiving">提交确认</BottomBtn>
		<!-- 提示弹窗 -->
		<messageTip ref="myMessage" />

	</view>

</template>

<script setup lang="ts">
	import BottomBtn from '@/components/bottomBtn/bottomBtn.vue';
	import Button1 from '@/components/button1/button1.vue';
	import Button2 from '@/components/button2/button2.vue';
	import StartProjectPopup from '@/components/consumption/startProjectPopup/startProjectPopup.vue';
	import MaterialTypePopup from '@/components/consumption/materialTypePopup/materialTypePopup.vue';
	import CarPlateInput from '@/components/carPlateInput/carPlateInput.vue';
	import PreviewImgs from '@/components/previewImgs/previewImgs.vue';
	import { computed, reactive, ref } from 'vue';
	import * as consumptionApi from '@/api/consumption/consumption.js';
	import * as dischargingApi from '@/api/consumption/discharging.js';

	import { useConsumptionStore } from '@/stroes';
	const consumptionStore = useConsumptionStore()
	const venueInfo = consumptionStore.nowVenue
	// 是否显示终点场所
	const isShowTerminusArea = ref(true)
	// 所有场所列表
	const allVenueList = ref([])
	// 起点场所
	const startVenueList = computed(() => {
		let data = allVenueList.value.find(item => item.label == startingPlace)
		let arr = data ? data.children : [];
		if (arr.length) {
			dischargingInfo.startingArea = data.children[0].label
		} else {
			dischargingInfo.startingArea = '无数据'
		}
		return arr
	})
	// 终点场所
	const endVenueList = computed(() => {
		let data = allVenueList.value.find(item => item.label == nowTerminusPlace.value)
		let arr = data ? data.children : [];
		if (arr.length) {
			dischargingInfo.terminusArea = data.children[0].label
		} else {
			dischargingInfo.terminusArea = '无数据'
		}
		return arr
	})
	// 修改起点场所
	const changeVenue1 = (item) => {
		dischargingInfo.startingArea = item.label
	}
	// 修改终点场所
	const changeVenue2 = (item) => {
		dischargingInfo.terminusArea = item.label
	}
	dischargingApi.getDischargingAddr({ label: venueInfo.terminalPointName }).then(res => {
		if (res.data.code == 0) {
			allVenueList.value = res.data.data
		}
	})
	// 消息提示
	const myMessage = ref()
	// 车辆号码
	const plateNumber = ref(['', '', '', '', '', '', '', ''])
	// 修改车辆号码
	const handleNumChange = (val : string[]) => {
		plateNumber.value = val
		dischargingInfo.carNumber = val.join('')
		if (val.length >= 7) {
			getCarInfoData(dischargingInfo.carNumber)
		}
	}
	const getCarInfoData = (carNum : string) => {
		let obj = {
			cartId: carNum
		}
		dischargingApi.getCartInfo(obj).then(res => {

			if (res.data.code == 0) {

				cartInfo.value = {
					plateNoType: res.data.data.plateNoType,
					companyName: res.data.data.vehicleInfo.companyName,
					directory: res.data.data.directory,
					companyId: res.data.data.vehicleInfo.companyId
				}
				dischargingInfo.transportCompanyId = res.data.data.vehicleInfo.companyId
				dischargingInfo.transportCompanyName = res.data.data.vehicleInfo.companyName
			} else {

				myMessage.value.open('error', res.data.msg)
			}
		})
	}
	// 收料信息
	const dischargingInfo = reactive({
		orderType: '2',
		"carImages": [],
		"rockImages": [],
		"carNumber": "",
		"driverName": "",
		// 起点id
		startingId: venueInfo.id,
		// 起点名称
		"startingPlace": venueInfo.terminalPointName,
		// 起点地址
		startingAddress: venueInfo.terminalPointAddress,
		startingLongitude: venueInfo.longitude,
		startingLatitude: venueInfo.latitude,
		startingArea: '',
		terminusArea: '',
		"startingType": '',
		// 起点厂区---4 原料厂
		startingFieldArea: '4',
		// 2 内转 3 销售
		"orderEnd": '2',
		// 终点项目名称
		"terminusPlace": "",
		terminusFieldArea: '5',
		"rockType": 0,
		"rockName": "",
		"fullFlag": "1",
		"volume": null,
		"reduceReason": "",
		"volumeReduce": null,
		"terminusId": null,
		"terminusAddress": "",
		"terminusLongitude": "",
		"terminusLatitude": "",
		"weighbridgeImages": [],
		transportCompanyId: '',
		transportCompanyName: '',
	})
	// 当前起点名称
	const startingPlace = '原料区';
	// 当前终点名称
	const nowTerminusPlace = computed(() => {
		if (dischargingInfo.orderEnd == '2') {
			return '生产区'
		}
		return ''
	})
	// 车辆信息
	const cartInfo = ref({})
	// 收料类型
	const orderTypeList = [{ name: '内转', id: '2' }, { name: '销售', id: '3' }]
	// 修改收料类型
	const changeOrderType = (id) => {
		dischargingInfo.orderEnd = id
		if (id == 3) {
			isShowTerminusArea.value = false
		} else {
			isShowTerminusArea.value = true
		}
	}

	// 上传车辆照片
	const uploadCartImg = () => {
		uni.chooseImage({
			count: 1,
			success: async (res) => {
				uni.showLoading({
					title: '正在识别中'
				})
				let res2 = await consumptionApi.uploadCartImg({ file: res.tempFilePaths })
				// console.log(res2, 'yyyyyyyyyyyy');
				if (res2.statusCode == 200) {
					let data = JSON.parse(res2.data).data
					dischargingInfo.carNumber = data.IdentifyCarNumber
					dischargingInfo.carImages = [data.ossUrl]
					// console.log(data, '888888888888');
					if (data.IdentifyCarNumber.length) {
						plateNumber.value = data.IdentifyCarNumber.split('')
					}
					let res3 = await dischargingApi.getCartInfo({ cartId: data.IdentifyCarNumber })
					// console.log(res3.data.data, 'uuuuuuuuu');
					if (res3.data.code == 0) {
						uni.hideLoading()
						cartInfo.value = {
							plateNoType: res3.data.data.plateNoType,
							companyName: res3.data.data.vehicleInfo.companyName,
							directory: res3.data.data.directory,
							companyId: res3.data.data.vehicleInfo.companyId
						}
						dischargingInfo.transportCompanyId = res3.data.data.vehicleInfo.companyId
						dischargingInfo.transportCompanyName = res3.data.data.vehicleInfo.companyName
					}
				}
				uni.hideLoading()

			}
		})
	}
	// 当前终点名称列表
	const addressList = ref([])
	// 是否显示终点项目弹窗
	const isShowStartProjectPopup = ref(false)
	// 打开选择终点项目弹窗
	const showStartProjectPopup = () => {
		dischargingApi.queryProjectInfoList().then(res => {
			if (res.data.code == 0) {
				addressList.value = res.data.data;
				isShowStartProjectPopup.value = true
			}
		})
	}
	// 保存终点项目
	const saveStartProject = (item) => {
		if (item) {
			dischargingInfo.terminusPlace = item.projectName
			dischargingInfo.terminusId = item.projectId
		}
		isShowStartProjectPopup.value = false
	}
	// 当前物料类型列表
	const muckTypeList = ref([])
	// 是否显示物料类型弹窗
	const isShowMaterialTypePopup = ref(false)
	// 显示物料类型弹窗
	const showMaterialTypePopup = () => {
		consumptionApi.muckTypeAll().then(res => {
			if (res.data.code == 0) {
				muckTypeList.value = res.data.data
			} else {
				console.log("失败")
			}
			isShowMaterialTypePopup.value = true
		})
	}
	// 保存物料类型
	const saveMaterialType = (item) => {
		if (item) {
			dischargingInfo.rockType = item.id
			dischargingInfo.rockName = item.name
		}
		isShowMaterialTypePopup.value = false
	}
	// 上传物料照片
	const uploadMaterialImg = (key) => {
		uni.chooseImage({
			count: 6,
			success: async (res) => {

				uni.showLoading({
					title: '正在上传中'
				})
				for (const file of res.tempFilePaths) {
					let res2 = await consumptionApi.uploadMaterialImg({ file })
					if (res2.data) {
						let data = JSON.parse(res2.data)
						dischargingInfo[key].push(data.data.ossUrl)
					}
				}
				uni.hideLoading()

			}
		})
	}
	// 是否显示更多图片
	const isShowMoreImgs = ref(false)

	// 关闭查看更多图片
	const closeMoreImgs = () => {
		isShowMoreImgs.value = false
	}

	// 满载列表
	const fullFlagList = [{ name: '是', id: '1' }, { name: '否', id: '0' },]
	// 修改满载类型
	const changeFullFlag = (id) => {
		if (id == '1') {
			dischargingInfo.volumeReduce = 0
		}
		dischargingInfo.fullFlag = id
	}
	// 开始添加收料
	let startAddReceiving = true
	// 保存新增收料
	const saveReceiving = () => {
		// return console.log(dischargingInfo, '55555');
		if (startAddReceiving) {
			startAddReceiving = false
			if (dischargingInfo.driverName == '' || dischargingInfo.rockName == '') {
				startAddReceiving = true
				return myMessage.value.open('error', '请将信息填写完整')
			}
			if (dischargingInfo.orderEnd == '2') {
				dischargingInfo.terminusPlace = '生产区'
				dischargingInfo.terminusLongitude = venueInfo.longitude + ''
				dischargingInfo.terminusLatitude = venueInfo.latitude + ''
			}
			dischargingApi.saveDischarge(dischargingInfo).then(res => {
				console.log('yyyyyyyyyyyyy', res, dischargingInfo);
				startAddReceiving = true
				if (res.data.code == 0) {
					myMessage.value.open('success', '新增收料成功')
					setTimeout(() => {
						uni.navigateBack({
							delta: 1, // 返回的页面数，如果 delta 大于现有页面数，则返回到首页。
							success: function () {
								uni.$emit('updata', { msg: "页面刷新" })
							},
							fail: function (err) {
								console.error('页面返回失败：', err);
							}
						});
					}, 1000)
				}
			})
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding-top: 208rpx;
		// padding-bottom: 300rpx;
		box-sizing: border-box;
	}

	.content {
		margin: 0rpx 32rpx;
		width: 686rpx;
		height: 1200rpx;
		font-size: 28rpx;
		color: $default-color;
		border-radius: 16rpx;
		background-color: #fff;
		overflow: hidden;


		.cart-imgs {
			display: flex;
			border-bottom: 2rpx solid rgba(156, 159, 163, 0.1);

			.left {
				flex: 1;
				padding: 32rpx 0rpx 20rpx 24rpx;

				.title {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
				}

				.upload-area {
					display: flex;
					font-size: 20rpx;
					color: $info-color;
					text-align: center;

					.upload-box {
						margin-right: 16rpx;

						.upload {
							display: flex;
							flex-direction: column;
							justify-content: center;
							align-items: center;
							margin-bottom: 10rpx;
							width: 135rpx;
							height: 136rpx;
							font-size: 24rpx;
							color: $primary-color;
							border: 2rpx dashed #9C9FA3;
							border-radius: 8rpx;

							.icon {
								width: 40rpx;
								height: 40rpx;
							}
						}


					}
				}

				.show-img {

					.imgs {
						display: flex;
						align-items: center;
						margin-bottom: 20rpx;

						.img {
							margin-right: 20rpx;
							width: 208rpx;
							height: 136rpx;
						}
					}

					.moreImg {
						text-align: left;
						font-size: 30rpx;
						color: $primary-color;
					}
				}
			}

			.upload-example {
				width: 200rpx;
				padding: 70rpx 20rpx 16rpx;
				box-shadow: -4rpx 0rpx 8rpx 0rpx rgba(0, 0, 0, 0.1);
				box-sizing: border-box;

				.img {
					width: 160rpx;
					height: 160rpx;
				}

				.example-tip {
					// margin-top: 10rpx;
					font-size: 20rpx;
					color: $primary-color;
					text-align: center;

				}
			}
		}

		.cart-info {
			padding: 18rpx;
			padding-left: 20rpx;

			.cart-types {
				margin-bottom: 18rpx;

				.btn {
					margin-right: 8rpx;
				}
			}

			.cart-type {
				font-size: 24rpx;
				text-align: right;
				color: #55CDA8;
			}
		}

		.cart-lines {
			.line {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
				border-top: 2rpx solid rgba(156, 159, 163, .1);
				border-bottom: 0rpx;

				.left {
					padding: 0;
				}

				.title {
					width: 30%;
					display: flex;
					align-items: center;

				}

				.val {
					display: flex;
					justify-content: flex-end;
					align-items: center;
					// font-weight: bold;

					.amount-input {
						margin: 0rpx 20rpx;
						width: 100rpx;
						font-size: 28rpx;
					}


					&.deduction-amount {
						color: #EB4F51;
					}

					&.no-check {
						color: #989DA5;
					}
				}

				.btn {
					margin-left: 8rpx;

					&.no-active-btn {
						color: $info-color;
						background: rgba(46, 135, 255, 0.1);
					}
				}

			}
		}

	}
</style>